#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#

module Luce
  # Escape ASCII punctuation preceded by a backslash.
  #
  # Backslashes before other characters are treated as literal backslashes.
  class EscapeSyntax < InlineSyntax
    # See https://spec.commonmark.org/0.30/#backslash-escapes.

    def initialize
      super("\\\\([#{Luce.ascii_punctuation_escaped}])", start_character: Charcode::BACKSLASH)
    end

    def on_match(parser : InlineParser, match : Regex::MatchData) : Bool
      chars = match[0]

      text = if %{&"<>}.includes?(match[1]) && parser.encode_html?
               Luce.escape_html(match[1])
             else
               chars[1].to_s
             end
      parser.add_node(Text.new(text))
      true
    end
  end
end
